package com.crt.uav.rabbitmq.consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;

import com.crt.uav.Constants;
import com.rabbitmq.client.Channel;

public abstract class AbstractExtChannelAwareMessageListener implements ExtChannelAwareMessageListener {

    private static final Logger logger = LoggerFactory.getLogger(AbstractExtChannelAwareMessageListener.class);

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try {
            // 处理消息
            String msgBody = new String(message.getBody());
            // 只消费记录日志
            logger.info("收到队列：" + message.getMessageProperties().getConsumerQueue() + "的消息: " + msgBody);       
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("队列：" + message.getMessageProperties().getConsumerQueue() + "消息已确认: " + msgBody);
        } catch (Exception e) {
            // 如果是重新入队的消息则不需要重新入队
            if (message.getMessageProperties().getRedelivered()) {
                // 拒绝消息
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                // 重新入队
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
            logger.error("队列：" + message.getMessageProperties().getConsumerQueue() + "消息处理失败，已重新入队: "
                    + new String(message.getBody()), e);

        } finally {
            if (Constants.PERSISTFLAG_YES.equals(getPersistFlag())) {
                try {
                    handelPersistMethod(message);
                } catch (Exception e) {
                    logger.error("持久化失败", e);
                }
            }
        }
    }

    /**
     * 获取队列名称
     * 
     * @return
     */
    @Override
    abstract public String getQueueName();

    /** 
     * 消息处理方法
     */
    protected void handleMessage(Message message, Channel channel){

    }

    /**
     * 获取持久化标志
     * 
     * @return
     */
    protected String getPersistFlag() {
        return Constants.PERSISTFLAG_NO;
    }

    /**
     * 持久化方法
     */
    protected void handelPersistMethod(Message message) {

        logger.info("持久化方法");
    }
}
